﻿using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace WindowsGame.GameObject
{
	/// <summary>
	/// SpaceShip is the only game object.
	/// </summary>
	public class SpaceShip
	{
		private Model spaceShipModel;
		private Matrix[] transforms;

		public SpaceShip()
		{
			ModelRotation = 0.0f;
			ModelPosition = Vector3.Zero;
			ModelVelocity = Vector3.Zero;
		}

		// Load model and set view/projection matrices.
		public void LoadContent(Model theSpaceShipModel, Matrix viewMatrix, Matrix projectionMatrix)
		{
			spaceShipModel = theSpaceShipModel;
			transforms = new Matrix[spaceShipModel.Bones.Count];
			spaceShipModel.CopyAbsoluteBoneTransformsTo(transforms);

			foreach (BasicEffect effect in spaceShipModel.Meshes.SelectMany(mesh => mesh.Effects.Cast<BasicEffect>()))
			{
				effect.EnableDefaultLighting();
				effect.View = viewMatrix;
				effect.Projection = projectionMatrix;
			}
		}

		// Update angle of rotation.
		public void Update(GameTime gameTime)
		{
			Single temps = MathHelper.ToRadians(0.05f);
			Single delta = (Single)gameTime.ElapsedGameTime.TotalMilliseconds;
			ModelRotation -= delta * temps;
		}

		// Draw model.
		public void Draw()
		{
			foreach (ModelMesh mesh in spaceShipModel.Meshes)
			{
				foreach (BasicEffect effect in mesh.Effects)
				{
					effect.World = transforms[mesh.ParentBone.Index]
						* Matrix.CreateRotationY(ModelRotation)
						* Matrix.CreateTranslation(ModelPosition);
				}

				mesh.Draw();
			}
		}

		public Single ModelRotation { get; private set; }
		public Vector3 ModelPosition { get; private set; }
		public Vector3 ModelVelocity { get; private set; }
	}
}